package com.javabasic.algorithm.leetcode;

import java.util.HashMap;
import java.util.Map;

/**
 * @author xiongmin
 * @version 0.0.1
 * @description Created by work on 2021/11/23 11:15 下午
 * @see
 */
public class BuddyStrings {

    public boolean buddyStrings(String s, String goal) {
        int lenS = s.length();
        int lenGoal = goal.length();

        if (lenGoal != lenS) return false;
        if (s.equals(goal)) {
            Map<Integer, Integer> map = new HashMap<>(2);
            for (int i = lenGoal; i > 0; i--) {
                int orDefault = map.getOrDefault(s.charAt(i) - 'a', 0);
                if (orDefault > 0) {
                    return true;
                }
                orDefault++;
                map.put(s.charAt(i) - 'a', orDefault);
            }
            return false;
        }

        int tag1 = 0, tag2 = lenGoal-1;
        for (int i = 0; i < lenGoal; i++) {
            if (s.charAt(i) != goal.charAt(i)) {
                tag1 = i;
                break;
            }
        }
        for (int i = lenGoal-1; i >= 0; i--) {
            if (s.charAt(i) != goal.charAt(i)) {
                tag2 = i;
                break;
            }
        }
        if (tag2 > tag1+1 && !s.substring(tag1+1,tag2).equals(goal.substring(tag1+1,tag2))) return false;

        System.out.println(tag1 + " " + tag2);
        if (s.charAt(tag1) == goal.charAt(tag2) && s.charAt(tag2) == goal.charAt(tag1)) {
            return true;
        } else {
            return false;
        }
    }
}
